<template>
	<view class="view-contain">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module leftIcon="arrow-left" :title="title" />
		<mescroll-uni :height="`${height}px`" :down="downOption" :up="upOption" @init="mescrollInit"
			@down="downCallback" @up="upCallback">
			<!-- 只显示一个试卷信息 -->
			<view class="province-item" v-if="papersList.length > 0" :key="papersList[0].id">
				<view class="paper-info">
					<view class="paper-title">{{ papersList[0].name }}</view>
				</view>
				<!-- 问题区域 -->
				<view class="questions-container">
					<view class="question-label" v-for="(question, questionIndex) in papersList[0].questions"
						:key="question.id" @click="showQuestionDetail(questionIndex)">
						问题 {{ questionIndex + 1 }}
					</view>
				</view>
				<view v-if="selectedQuestionIndex !== null">
					<view class="question-detail">
						<view class="question-title">问题:</view>
						<view class="question-description">
							{{ papersList[0].questions[selectedQuestionIndex].description }}
						</view>
						<view class="answer-title-container">
							<view class="answer-title">参考答案:</view>
							<view class="expand-btn" @click="toggleAllAnswers">
								<u-icon :name="allAnswersExpanded ? 'arrow-up' : 'arrow-down'" size="28" color="#2979ff"></u-icon>
								<text class="expand-text">{{ allAnswersExpanded ? '收起' : '展开' }}</text>
							</view>
						</view>
						<view class="answers-container">
							<view class="answer-label"
								v-for="(answer, answerIndex) in papersList[0].questions[selectedQuestionIndex].answers"
								:key="answer.id">
								<view class="answer-source-and-stats">
									<!-- 新增文字答案来源，使用 u-parse 组件显示富文本 -->
									<view class="answer-source" @click="toggleAnswerContent(answerIndex)">
										<u-parse :content="answer.source"></u-parse>
									</view>
									<view class="answer-stats">
										<view class="like-count" @click="toggleLike(answerIndex)">
											<u-icon :name="likeStatus[answerIndex] ? 'thumb-up-fill' : 'thumb-up'"
												:size="30" />
											<text> {{ answer.likeCount !== null ? answer.likeCount : 0 }} </text>
										</view>
									</view>
								</view>
								<!-- 答案内容另起一行，默认隐藏 -->
								<view class="answer-content" v-if="visibleAnswerIndexes.includes(answerIndex)">
									<!-- 使用 u-parse 组件显示答案内容的富文本 -->
									<u-parse :content="answer.content"></u-parse>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-uni>
	</view>
</template>

<script>
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import {
		paperDetail,
		answerLike
	} from "@/config/api.js";
	import uParse from '@/uni_modules/uview-ui/components/u-parse/u-parse.vue'; // 引入 u-parse 组件

	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			uParse // 注册 u-parse 组件
		},
		data() {
			return {
				title: '参考答案',
				height: 0,
				category: '',
				papersList: [],
				downOption: {
					use: false
				},
				upOption: {
					use: false // 禁用上拉加载
				},
				selectedQuestionIndex: null,
				visibleAnswerIndexes: [], // 用于记录每个问题下可见答案的索引
				likeStatus: [], // 用于记录每个答案的点赞状态
				allAnswersExpanded: false // 记录是否展开全部答案
			}
		},
		computed: {},
		onLoad(option) {
			const {
				id
			} = option;
			this.id = id;
			console.log("当前试卷ID " + this.id);

			// 默认打开问题1
			this.selectedQuestionIndex = 0; // 设置为第一个问题的索引

			// 加载数据
			this.loadData();
		},
		onShow() {
			const res = uni.getWindowInfo()
			this.height = res.windowHeight
		},
		methods: {
			async loadData() {
				try {
					const res = await paperDetail(`${this.id}`);
					if (res) {
						this.papersList = [res.data]; // 确保只显示一个试卷信息
						// 根据后端返回的 isLiked 初始化 likeStatus 数组
						if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
							const answers = this.papersList[0].questions[this.selectedQuestionIndex].answers;
							this.likeStatus = answers.map(answer => answer.isLiked === 1);
						}
					} else {
						uni.showModal({
							title: '提示',
							content: '当前登录已无效，请重新登陆。',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									uni.navigateBack({
										delta: 1
									});
								}
							}
						});
					}
				} catch (error) {
					console.error('数据加载失败:', error);
				}
			},
			showQuestionDetail(index) {
				this.selectedQuestionIndex = index; // 设置选中的问题索引
				this.visibleAnswerIndexes = []; // 切换问题时清空可见答案索引
				this.allAnswersExpanded = false; // 切换问题时重置展开状态
				// 切换问题时更新 likeStatus 数组
				if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
					const answers = this.papersList[0].questions[this.selectedQuestionIndex].answers;
					this.likeStatus = answers.map(answer => answer.isLiked === 1);
				}
			},
			toggleAnswerContent(answerIndex) {
				const index = this.visibleAnswerIndexes.indexOf(answerIndex);
				if (index > -1) {
					this.visibleAnswerIndexes.splice(index, 1); // 隐藏答案
				} else {
					this.visibleAnswerIndexes.push(answerIndex); // 显示答案
				}
				// 检查是否所有答案都已展开
				if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
					const totalAnswers = this.papersList[0].questions[this.selectedQuestionIndex].answers.length;
					this.allAnswersExpanded = this.visibleAnswerIndexes.length === totalAnswers;
				}
			},
			toggleAllAnswers() {
				if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
					const totalAnswers = this.papersList[0].questions[this.selectedQuestionIndex].answers.length;
					if (this.allAnswersExpanded) {
						// 收起全部答案
						this.visibleAnswerIndexes = [];
						this.allAnswersExpanded = false;
					} else {
						// 展开全部答案
						this.visibleAnswerIndexes = Array.from({ length: totalAnswers }, (_, i) => i);
						this.allAnswersExpanded = true;
					}
				}
			},
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			downCallback() {
				// 下拉刷新回调，这里禁用了下拉刷新，可留空
			},
			upCallback() {
				// 上拉加载回调，这里禁用了上拉加载，可留空
			},
			async toggleLike(answerIndex) {
				const currentAnswer = this.papersList[0].questions[this.selectedQuestionIndex].answers[answerIndex];
				const answerId = currentAnswer.id; // 获取当前答案的 ID

				// 取消同一问题下其他答案的喜欢状态
				this.papersList[0].questions[this.selectedQuestionIndex].answers.forEach((answer, index) => {
					if (index !== answerIndex) {
						this.likeStatus[index] = false; // 取消其他答案的喜欢状态
						answer.isLiked = 0; // 更新 isLiked 字段
						this.papersList[0].questions[this.selectedQuestionIndex].answers[index].likeCount =
							this.papersList[0].questions[this.selectedQuestionIndex].answers[index].likeCount >
							0 ?
							this.papersList[0].questions[this.selectedQuestionIndex].answers[index].likeCount -
							1 :
							0; // 减少其他答案的点赞数量
					}
				});

				// 切换当前答案的点赞状态
				const isLiked = this.likeStatus[answerIndex];
				this.likeStatus[answerIndex] = !isLiked;
				currentAnswer.isLiked = this.likeStatus[answerIndex] ? 1 : 0; // 更新 isLiked 字段

				// 更新当前答案的点赞数量
				if (this.likeStatus[answerIndex]) {
					this.papersList[0].questions[this.selectedQuestionIndex].answers[answerIndex].likeCount++;
					// 调用后端接口进行点赞
					await answerLike(answerId); // 发送请求
				} else {
					this.papersList[0].questions[this.selectedQuestionIndex].answers[answerIndex].likeCount--;
					// 这里可以选择是否调用后端接口进行取消点赞
					// await answerUnlike(answerId); // 如果有取消点赞的接口
				}
			}
		},
		mounted() {
			// 初始化点赞状态
			if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
				const answers = this.papersList[0].questions[this.selectedQuestionIndex].answers;
				this.likeStatus = answers.map(answer => answer.isLiked === 1);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.view-contain {
		flex-direction: column;
		align-items: center;
		background-color: #F5F6F5;
		height: 100vh;
		padding: 20px 8px;
		/* 增加顶部内边距以适配刘海屏 */
	}

	.welcome-message {
		margin-bottom: 20px;
		font-size: 18px;
		color: #333;
	}

	.province-list {
		width: 100%;
	}

	.province-item {
		justify-content: space-between;
		align-items: center;
		width: 100%;
		margin-bottom: 5px;
		border-radius: 5px;
	}

	.arrow {
		font-size: 18px;
		color: #333;
	}

	.paper-info {
		margin-bottom: 20px;
		/* 添加底部间距 */
	}

	.paper-title {
		font-size: 18px;
		/* 调整试卷名称字体大小 */
		text-align: center; // 文字居中对齐
	}

	.questions-container {
		display: flex;
		flex-wrap: wrap;
		margin-top: 10px;
		padding: 8px;
	}

	.question-label {
		flex: 0 0 14%;
		margin-bottom: 10px;
		padding: 5px 10px;
		background-color: #E0F7FA;
		border-radius: 5px;
		cursor: pointer;
		text-align: center;
	}

	.question-detail {
		margin-top: 20px;
	}

	.question-title {
		font-weight: bold;
		margin-bottom: 5px;
	}

	.question-description {
		margin-bottom: 10px;
		text-indent: 2em;
		width: 98%;
	}

	.answer-title-container {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 10px;
		padding: 0 10px;
	}

	.answer-title {
		font-weight: bold;
	}

	.expand-btn {
		display: flex;
		align-items: center;
		gap: 5px;
		cursor: pointer;
		padding: 5px 10px;
		border-radius: 5px;
		transition: all 0.3s;
		min-width: 60rpx;
		min-height: 60rpx;
		justify-content: center;
	}

	.expand-btn:active {
		opacity: 0.7;
		background-color: rgba(41, 121, 255, 0.1);
	}

	.expand-text {
		font-size: 14px;
		color: #2979ff;
	}

	.answers-container {
		display: flex;
		flex-direction: column;
		/* 列表模式 */
		margin-top: 10px;
	}

	.answer-label {
		margin-bottom: 5px;
		padding: 10px;
		background-color: #E0F7FA;
		border-radius: 5px;
		cursor: pointer;
	}

	.answer-source-and-stats {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		flex-direction: row;
		padding: 0 15px; // 添加左右内边距
	}

	.answer-source {
		cursor: pointer;
		width: 40%;
		margin-left: 0; // 左对齐，移除左边距
		text-align: left; // 确保文字左对齐
	}

	.answer-stats {
		display: flex;
		justify-content: space-between;
		margin-right: 25px; // 添加右边距
	}

	.like-count {
		display: flex;
		align-items: center;
		cursor: pointer;
	}

	.active {
		color: #007AFF; // 设置激活状态的颜色
	}

	.answer-content {
		margin-top: 10px;
		font-weight: normal;
		width: 98%;
		
		/* 为答案内容中的段落添加首行缩进 */
		::v-deep p {
			text-indent: 2em;
			margin-bottom: 10px;
			line-height: 1.6;
		}
		
		/* 为答案内容中的div添加首行缩进 */
		::v-deep div {
			text-indent: 2em;
			line-height: 1.6;
		}
		
		/* 确保富文本内容换行 */
		::v-deep * {
			word-wrap: break-word;
			word-break: break-all;
		}
	}

	.selected-answer-content {
		margin-top: 20px;
		padding: 10px;
		background-color: #E0F7FA;
		border-radius: 5px;
	}
</style>